#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/gpio.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_gpio.h>
#include <linux/semaphore.h>
#include <linux/timer.h>
// #include <asm/mach/map.h>
#include <asm/uaccess.h>
#include <asm/io.h>

#define DEVICE_CNT 1         // 设备号个数
#define TIME_NAME "time_led" // 设备名称

#define CLOSE_CMD (_IO(0XEF, 0x1))     /* 关闭定时器 */
#define OPEN_CMD (_IO(0XEF, 0x2))      /* 打开定时器 */
#define SETPERIOD_CMD (_IO(0XEF, 0x3)) /* 设置定时器周期命令 */

/* timer 设备结构体 */
struct timer_dev
{
    dev_t devid;             /* 设备号 */
    struct cdev cdev;        /* cdev */
    struct class *class;     /* 类 */
    struct device *device;   /* 设备 */
    int major;               /* 主设备号 */
    int minor;               /* 次设备号 */
    struct device_node *nd;  /* 设备节点 */
    int led_gpio;            /* key 所使用的 GPIO 编号 */
    int timeperiod;          /* 定时周期,单位为 ms */
    struct timer_list timer; /* 定义一个定时器 */
    spinlock_t lock;         /* 定义自旋锁 */
};

static struct timer_dev timer_dev;

static int led_init(void)
{
    int ret = -1;
    const char *str;

    /* 设置LED使用的GPIO*/
    /*1. 获取设备树节点*/
    timer_dev.nd = of_find_node_by_path("/gpio_led");
    if (timer_dev.nd == NULL)
    {
        printk("<0>device tree node 'led' not find!\r\n");
        return -EINVAL;
    }
    /* 2. 读取status属性值*/
    ret = of_property_read_string(timer_dev.nd, "status", &str);
    if (ret < 0)
    {
        printk("<0>read status property failed!\r\n");
        return -EINVAL;
    }

    if (strcmp(str, "okay")) // 判断状态  > 0 则返回失败
    {
        return -EINVAL;
    }
    /* 3. 获取compatible属性值并进行匹配 */
    ret = of_property_read_string(timer_dev.nd, "compatible", &str);

    if (ret < 0)
    {
        printk("<0>read compatible property failed!\r\n");
        return -EINVAL;
    }

    if (strcmp(str, "alientek,led"))
    {
        printk("gpioled: Compatible match failed\r\n");
        return -EINVAL;
    }
    /* 4. 获取gpio属性值 得到LED 所使用的 GPIO 编号*/
    timer_dev.led_gpio = of_get_named_gpio(timer_dev.nd, "led-gpio", 0);
    if (timer_dev.led_gpio < 0)
    {
        printk("<0>read led-gpios property failed!\r\n");
        return -EINVAL;
    }
    printk("led gpio num = %d\r\n", timer_dev.led_gpio);

    /* 5. 向gpio子系统申请一个gpio*/
    ret = gpio_request(timer_dev.led_gpio, "LED");
    if (ret < 0)
    {
        printk(KERN_ERR "<0>request led-gpios failed!\r\n");
        return ret;
    }

    /* 6. 设置gpio为输出模式并且输出低电平*/
    ret = gpio_direction_output(timer_dev.led_gpio, 0);
    if (ret < 0)
    {
        printk(KERN_ERR "<0>set led-gpios failed!\r\n");
    }
    return 0;
}

static int timer_open(struct inode *inode, struct file *filp)
{
    int ret = 0;
    filp->private_data = &timer_dev; // 设置私有数据

    timer_dev.timeperiod = 1000; /* 默认周期为 1s */
    ret = led_init();           /* 初始化 LED IO */
    if (ret < 0)
    {
        return ret;
    }
    return 0;
}

/**
 * @description : 设备控制函数
 * @param : filp 文件指针
 * @param : cmd 命令
 * @param : arg 参数
 */
static long timer_unlocked_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
    struct timer_dev *dev = (struct timer_dev *)filp->private_data;
    int timerperiod; // 定时器周期
    unsigned long flags;
    switch (cmd)
    {
    case CLOSE_CMD:
        {
            del_timer_sync(&dev->timer); // 删除定时器
            break;
        }
    case OPEN_CMD: // 打开定时器
        {
            spin_lock_irqsave(&dev->lock, flags);// 申请锁
            timerperiod = dev->timeperiod;
            spin_unlock_irqrestore(&dev->lock, flags);// 释放锁
            mod_timer(&dev->timer, jiffies + msecs_to_jiffies(timerperiod));
                printk("timer start!\r\n");
                break;
        }
    case SETPERIOD_CMD:
        {
            spin_lock_irqsave(&dev->lock, flags);
            dev->timeperiod = arg;
            spin_unlock_irqrestore(&dev->lock, flags);
            mod_timer(&dev->timer, jiffies + msecs_to_jiffies(arg));
            printk("timer period = %d\r\n", timerperiod); 
            break;
        }
        default:
            break;
    }
    return 0;
}



static int led_release(struct inode *inode, struct file *filp)
{
    
    struct timer_dev *dev = filp->private_data;
    gpio_set_value(dev->led_gpio, 0); /* APP 结束的时候关闭 LED */
    gpio_free(dev->led_gpio);
    del_timer_sync(&dev->timer);
    return 0;
}

/* 设备操作函数 */
static struct file_operations timer_fops = {
    .owner = THIS_MODULE,
    .open = timer_open,
    .unlocked_ioctl = timer_unlocked_ioctl,
    .release = led_release,
};

/* 定时器回调函数 */
static void timer_callback(struct timer_list *arg)
{
    struct timer_dev *dev = from_timer(dev, arg, timer);
    static int count;
    static int sta = 1;

    int timerperiod;
    unsigned long flags;

    sta = !sta; /* 每次都取反，实现 LED 灯反转 */
    gpio_set_value(dev->led_gpio, sta);
     /* 重启定时器 */
    spin_lock_irqsave(&dev->lock, flags);
    timerperiod = dev->timeperiod;
    spin_unlock_irqrestore(&dev->lock, flags);
    mod_timer(&dev->timer, jiffies +msecs_to_jiffies(dev->timeperiod));
    printk("timer callback! %d\r\n",count++);

}

/*
 * @description : 驱动入口函数
 * @param : 无
 * @return : 无
 */
static int __init timer_init(void)
{
    int ret = -1;
    

    // 初始化锁
    spin_lock_init(&timer_dev.lock);

    /* 7. 注册字符设备驱动 */
    if (timer_dev.major)
    {
        timer_dev.devid = MKDEV(timer_dev.major, 0);
        ret = register_chrdev_region(timer_dev.devid, DEVICE_CNT, TIME_NAME);
        if (ret < 0)
        {
            pr_err("cannot register %s char driver [ret=%d]\n",
                   TIME_NAME, DEVICE_CNT);
            goto free_gpio;
        }
    }
    else
    {
        ret = alloc_chrdev_region(&timer_dev.devid, 0, DEVICE_CNT, TIME_NAME);
        if (ret < 0)
        {
            pr_err("%s Couldn't alloc_chrdev_region,ret=%d\r\n",
                   TIME_NAME, ret);
            goto free_gpio;
        }
        timer_dev.major = MAJOR(timer_dev.devid);
        timer_dev.minor = MINOR(timer_dev.devid);
    }
    printk("major=%d, minor=%d\r\n", timer_dev.major, timer_dev.minor);
    // 创建字符设备
    timer_dev.cdev.owner = THIS_MODULE;
    cdev_init(&timer_dev.cdev, &timer_fops);
    ret = cdev_add(&timer_dev.cdev, timer_dev.devid, DEVICE_CNT);
    if (ret < 0)
    {
        pr_err("cdev_add failed,ret=%d\r\n", ret);
        goto del_unregister;
    }
    /* 8. 创建类 */
    timer_dev.class = class_create(THIS_MODULE, TIME_NAME);
    if (IS_ERR(timer_dev.class))
    {
        goto del_cdev;
    }
    /* 9. 创建设备 */
    timer_dev.device = device_create(timer_dev.class, NULL, timer_dev.devid, NULL, TIME_NAME);
    if (IS_ERR(timer_dev.device))
    {
        goto destroy_class;
    }
    /* 6、初始化 timer，设置定时器处理函数,还未设置周期，所有不会激活定时器 */
    timer_setup(&timer_dev.timer, timer_callback, 0);
    return 0;
destroy_class:
    class_destroy(timer_dev.class);
del_cdev:
    cdev_del(&timer_dev.cdev);
del_unregister:
    unregister_chrdev_region(timer_dev.devid, DEVICE_CNT);
free_gpio:
    gpio_free(timer_dev.led_gpio);
    return -EIO;
}

void __exit timer_exit(void)
{
    del_timer_sync(&timer_dev.timer); /* 删除 timer */
#if 0
   del_timer(&timer_dev.tiemr);
#endif
       

    cdev_del(&timer_dev.cdev);
    unregister_chrdev(DEVICE_CNT, TIME_NAME);
    device_destroy(timer_dev.class, timer_dev.devid); /* 注销设备 */
    class_destroy(timer_dev.class);                 /* 注销类 */
    gpio_free(timer_dev.led_gpio);                  /* 释放 GPIO */
    printk("led exit ok!\r\n");
}

module_init(timer_init);
module_exit(timer_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("JACK");
MODULE_INFO(intree, "Y");
